package controllers

import (
	"fmt"
	"strconv"
	"strings"
	// "time"

	m "myerp/models"
	pg "myerp/src"
)

type UserController struct {
	CommonController
}

func (c *UserController) List() {
	//iDisplayStart := c.GetString("iDisplayStart", "0")
	iDisplayLength := c.GetString("iDisplayLength", "10")
	//iStart, _ := strconv.Atoi(iDisplayStart)
	iLength, _ := strconv.Atoi(iDisplayLength)
	page, _ := c.GetInt("page", 0)
	//count, _ := m.Users()
	users, count := m.GetUserList(int64(page+1), int64(iLength), "Id")
	for _, user := range users {
		switch user["Status"] {
		case int64(1):
			user["Statusname"] = "正常"
		case int64(2):
			user["Statusname"] = "禁止"
		default:
			user["Statusname"] = "不正常"
		}

		role := m.GetRoleByUserId(user["Id"].(int64))
		user["Rolename"] = role.Name
	}

	// data := make(map[string]interface{})
	// data["aaData"] = users
	// data["iTotalDisplayRecords"] = count
	// data["iTotalRecords"] = iLength
	c.Data["List"] = users
	var pages pg.Page = pg.NewPage(page+1, iLength, int(count), "/user/list")
	c.Data["page"] = pages.Show()
	c.Layout = "base.html"
	c.TplName = "user/list.html"

}

// 显示用户信息
func (c *UserController) Show() {

}

//就是代表更新
func (c *UserController) Edit() {

	isAction := c.GetString("isAction")

	Id, _ := c.GetInt64("id")
	Uname := c.GetString("name")
	Pwd := c.GetString("pwd")
	Nickname := c.GetString("nickname")
	Email := c.GetString("email")
	Phone := c.GetString("phone")
	Status, _ := c.GetInt64("status")
	Remark := c.GetString("remark")
	// Logintime := c.GetString("Logintime")
	// Ctime := c.GetString("Ctime")

	user := new(m.User)
	user.Id = Id
	user.Uname = strings.TrimSpace(Uname)
	user.Pwd = strings.TrimSpace(Pwd)
	user.Nickname = strings.TrimSpace(Nickname)
	user.Email = Email
	user.Phone = Phone
	user.Status = Status
	user.Remark = Remark

	if "0" == isAction {
		_, err := m.UpdateUser(user)
		if err != nil {
			c.Rsp(false, "更新出现问题："+err.Error())
		} else {
			c.Ctx.Redirect(302, "/user/list.html")
		}
	} else {
		c.Data["Resource"] = user
		c.Layout = "base.html"
		c.TplName = "user/edit.html"
	}

}

// 添加用户
func (c *UserController) Add() {
	if c.Ctx.Request.Method == "POST" {
		name := c.GetString("name")
		nickname := c.GetString("nickname")
		pwd := c.GetString("pwd")
		email := c.GetString("email")
		telphone := c.GetString("telphone")
		remark := c.GetString("remark")
		status, _ := c.GetInt64("status")

		// user := new(m.User)
		user := m.GetUserByUname(name)
		if user.Id == 0 {
			user.Uname = name
			user.Nickname = nickname
			user.Pwd = pwd
			user.Email = email
			user.Phone = telphone
			user.Remark = remark
			user.Status = status

			_, err := m.AddUser(&user)
			if err != nil {
				fmt.Println("插入数据库错误或者已经插入")
				fmt.Println(err)
				return
			}
		} else {
			fmt.Println("已经插入")
			c.Rsp(false, "已经插入")
		}

		c.Ctx.Redirect(302, "user/add.html")
	} else {
		c.Layout = "base.html"
		c.TplName = "user/add.html"
	}

}

// 删除用户  逻辑删除
func (c *UserController) Delete() {
	ajaxReturn := make(map[string]interface{})
	Id, _ := c.GetInt64("Id")
	if Id < 0 {
		ajaxReturn["status"] = 0
		ajaxReturn["msg"] = "删除的账户不存在"
		c.Data["json"] = ajaxReturn
		c.ServeJSON()
		return
	}
	_, err := m.DelUserById(Id)
	if err != nil {
		ajaxReturn["status"] = 0
		ajaxReturn["msg"] = "删除失败"
	} else {
		ajaxReturn["status"] = 1
		ajaxReturn["msg"] = "删除成功"

	}
	c.Data["json"] = ajaxReturn
	c.ServeJSON()
}

//禁用用户
func (c *UserController) Disuser() {
	ajaxReturn := make(map[string]interface{})
	Id, _ := c.GetInt("id")
	fmt.Println(Id)
	if Id < 0 {
		ajaxReturn["status"] = 0
		ajaxReturn["msg"] = "禁用的账户不存在"
		c.Data["json"] = ajaxReturn
		c.ServeJSON()
		return
	}
	status, _ := c.GetInt("st", 1)
	if status == 1 {
		status = 2
	} else {
		status = 1
	}
	err := m.DisableUserByid(Id, status)
	if err != nil {
		ajaxReturn["status"] = 0
		if status == 1 {
			ajaxReturn["msg"] = "启用失败"
		} else {
			ajaxReturn["msg"] = "禁用失败"
		}
	} else {
		ajaxReturn["status"] = 1
		if status == 1 {
			ajaxReturn["msg"] = "启用成功"
		} else {
			ajaxReturn["msg"] = "禁用成功"
		}
	}
	c.Data["json"] = ajaxReturn
	c.ServeJSON()
}

// 给用户分配角色
func (c *UserController) AllocationRole() {
	Id, _ := c.GetInt64("Id")
	fmt.Printf("给用户分配角色 Id is %d\n", Id)
	err, user := m.IsExitUser(Id)
	roleByUser := m.GetRoleByUserId(Id)

	roles, _ := m.GetAllRole()
	if err != nil {
		c.Rsp(false, "不存在这个用户")
	} else {
		c.Data["User"] = &user
		roleList := make([]m.Role, len(roles))
		for k, role := range roles {
			roleList[k].Id = role["Id"].(int64)
			roleList[k].Name = role["Name"].(string)
			roleList[k].Key = role["Key"].(string)
			roleList[k].Description = role["Description"].(string)
			roleList[k].Status = role["Status"].(int64)
			if roleList[k].Status == 2 {
				roleList[k].Isnormal = true
			} else {
				roleList[k].Isnormal = false
			}

		}
		c.Data["RoleList"] = &roleList
		c.Data["UserRole"] = roleByUser.Name
		c.TplName = "user/userRole.html"
	}
}

func (c *UserController) Allocation() {
	userId, _ := c.GetInt64("userId")
	roleId, _ := c.GetInt64("roleId")
	fmt.Printf("userId is %d and roleId is %d\n", userId, roleId)
	errId := m.DelUserRoleByUserId(userId)
	fmt.Println(errId)
	_, err := m.AddRoleUser(roleId, userId)
	// fmt.Println(err.Error())
	if err != nil {
		c.Rsp(false, "分配权限失败")
		fmt.Println("分配权限失败")
	} else {
		c.Rsp(true, "分配权限成功")
	}

}
